package cn.topcodes.tcsf.cms.web.controller;

import cn.topcode.unicorn.utils.ValidationUtil;
import cn.topcodes.tcsf.admin.commons.api.domain.ApiResponseEntity;
import cn.topcodes.tcsf.cms.domain.entity.ArticleCatalog;
import cn.topcodes.tcsf.cms.domain.vo.ArticleCatalogVo;
import cn.topcodes.tcsf.cms.domain.form.ArticleCatalogForm;
import cn.topcodes.tcsf.admin.commons.api.controller.admin.AdminController;
import cn.topcodes.tcsf.cms.domain.vo.NestableSort;
import cn.topcodes.tcsf.cms.service.ArticleCatalogService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 文章分类管理控制器
 *
 * @author Unicorn
 * @date 2017-12-25 21:34:53
 */
@Controller
@RequestMapping("/admin/cms/article-catalog")
public class ArticleCatalogController extends AdminController<ArticleCatalog, ArticleCatalogVo, ArticleCatalogForm> {

    @Autowired
    private ArticleCatalogService articleCatalogService;

    @Override
    protected String getPageFolder() {
        return "/cms/article-catalog";
    }

    @RequestMapping("save-sort")
    @ResponseBody
    public ApiResponseEntity saveSort(@RequestBody(required = true) List<NestableSort> sort) {

        articleCatalogService.saveSort(sort);
        return ApiResponseEntity.buildOK();
    }

    @Override
    public ApiResponseEntity create(HttpServletRequest request,
                                    @Valid @ApiParam("创建资源表单") ArticleCatalogForm form, BindingResult result) {
        ValidationUtil.validate(result);
        ArticleCatalog entity = this.form2Entity(form);
        entity.setSort(0);
        Long id = articleCatalogService.create(entity);
        return ApiResponseEntity.buildOK().setBody(id);
    }

    @Override
    public ApiResponseEntity<Void> update(HttpServletRequest request, @Valid @ApiParam("更新资源表单") ArticleCatalogForm form, BindingResult result) {

        ArticleCatalog t = this.form2Entity(form);
        ArticleCatalog articleCatalog = articleCatalogService.findOne(form.getId());
        t.setSort(articleCatalog.getSort());
        t.setParentId(articleCatalog.getParentId());
        articleCatalogService.update(t);
        return ApiResponseEntity.buildOK();
    }
}
